package hu.szyrt.bug.connections;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;

import hu.szyrt.bug.R;
import hu.szyrt.bug.utils.Config;

public class FacebookConnection extends BaseConnection {

	private int memberID = -1;
	private String resultText = null;
	private String facebookID, 
				   facebookName, 
				   facebookEmail;
	
	private Activity activity;
	private Facebook facebook;
	private AsyncFacebookRunner asyncFacebook;
	
	
	public FacebookConnection(Activity activity) {
		super(Config.URL_BUG_FACEBOOK);
		this.params.put("facebook", "Y");
		this.activity = activity;
		this.facebook = new Facebook(Config.FB_APP_ID);		
	}
	
	
	@Override
	public void run() {
		
		this.params.put("name", facebookName);
		this.params.put("email", facebookEmail);
		parameterizedURL();
		if(download()){
			// JSON decode
			try {
				JSONObject jsonResult = new JSONObject(rawResults);
				this.resultText = jsonResult.getString("result_text");
				this.memberID = jsonResult.getInt("member_id");				
				if (jsonResult.getBoolean("result")) postSuccess();
				else 								 postError();							
			} catch (JSONException e) {
				e.printStackTrace();
				postError();
			}
		}else{
			postError();
		}	
		
	}
	
	@Override
	public synchronized void start() {

		// 1. lépés: hozzáférést kérünk
		this.asyncFacebook = new AsyncFacebookRunner(facebook);
		this.facebook.authorize(activity, new String[]{"email"}, new Facebook.DialogListener() {
			public void onFacebookError(FacebookError e) {
				errorText = e.getMessage();
				postError();
			}			
			public void onError(DialogError e) {
				errorText = e.getMessage();
				postError();
			}
			
			public void onComplete(Bundle values) {
				// 2. lépés: Lekérjük az adatait
				asyncFacebook.request("me", new RequestListener() {
					public void onMalformedURLException(MalformedURLException e, Object state) {
						errorText = e.getMessage();
						e.printStackTrace();
						postError();
					}					
					public void onIOException(IOException e, Object state) {
						errorText = e.getMessage();
						e.printStackTrace();
						postError();
					}					
					public void onFileNotFoundException(FileNotFoundException e, Object state) {
						errorText = e.getMessage();
						e.printStackTrace();
						postError();
					}					
					public void onFacebookError(FacebookError e, Object state) {
						errorText = e.getMessage();
						e.printStackTrace();
						postError();
					}					
					public void onComplete(String response, Object state) {
						try {
							JSONObject json = Util.parseJson(response);
							facebookID = json.getString("id");
	                        facebookName = json.getString("name");
	                        facebookEmail = json.getString("email");
	                        
	                        //Log.d("bug", "---->>>> " + facebookName + " (" + facebookEmail + ")");
	                        
	                        // 3. lépés regisztrálás BUG szerveren
	                        FacebookConnection.super.start();
						} catch (FacebookError e) {
							errorText = e.getMessage();
							e.printStackTrace();
							postError();
						} catch (JSONException e) {
							errorText = e.getMessage();
							e.printStackTrace();
							postError();
						}
					}
				});
			}			
			public void onCancel() {
				Toast.makeText(activity, R.string.cancel, Toast.LENGTH_LONG).show();				
			}
		});
	}
	
	public void shareAndPostOnWall(final String message, final String name, final String caption, final String description, final String link, final String picture){
		facebook.authorize(activity, new String[]{"publish_stream"}, new Facebook.DialogListener() {			
			public void onComplete(Bundle values) {
				Bundle parameters = new Bundle();
		         	   parameters.putString("message", message);// the message to post to the wall
		         	   parameters.putString("name", name);
		         	   parameters.putString("caption", caption);
		         	   parameters.putString("description", description);
		         	   parameters.putString("link", link);
		         	   parameters.putString("picture", picture);
		        facebook.dialog(activity, "stream.publish", parameters, new Facebook.DialogListener() {			
					public void onComplete(Bundle values) {			
						postSuccess();
					}			
					public void onCancel() {
						Toast.makeText(activity, R.string.cancel, Toast.LENGTH_LONG).show();
					}
					public void onFacebookError(FacebookError e) {
						errorText = e.getMessage();
						e.printStackTrace();
						postError();
					}
					public void onError(DialogError e) {
						errorText = e.getMessage();
						e.printStackTrace();
						postError();
					}
				});
			}
			public void onCancel() {
				Toast.makeText(activity, R.string.cancel, Toast.LENGTH_LONG).show();
			}
			public void onFacebookError(FacebookError e) {
				errorText = e.getMessage();
				e.printStackTrace();
				postError();
			}			
			public void onError(DialogError e) {
				errorText = e.getMessage();
				e.printStackTrace();
				postError();
			}			
		});
	}
	
		
	public void facebookAuthorizeCallback(int requestCode, int resultCode, Intent data){
		this.facebook.authorizeCallback(requestCode, resultCode, data);
	}
	
	
	// Setters --------------------------
	public void setUserName(String name){
		this.params.put("name", name);
	}
	
	public void setEmail(String email){
		this.params.put("email", email);		
	}
	
	
	// Getters --------------------------
	public int getMemberID() {
		return memberID;
	}
	
	public String getResultText() {
		return resultText;
	}
	
	public String getFacebookEmail() {
		return facebookEmail;
	}
	
	public String getFacebookID() {
		return facebookID;
	}
	
	public String getFacebookName() {
		return facebookName;
	}
	

}
